package com.karry.yl.web.elder;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.karry.commons.base.SuperController;
import com.karry.commons.vo.JsonResponse;
import com.karry.commons.vo.LayTableResponse;
import com.karry.yl.domain.baseinfo.Bed;
import com.karry.yl.domain.baseinfo.Building;
import com.karry.yl.domain.baseinfo.Room;
import com.karry.yl.domain.elder.*;
import com.karry.yl.domain.healthdata.HealthData;
import com.karry.yl.domain.personnel.Department;
import com.karry.yl.domain.services.Meal;
import com.karry.yl.domain.services.Records;
import com.karry.yl.service.baseinfo.BedService;
import com.karry.yl.service.baseinfo.BuildingService;
import com.karry.yl.service.baseinfo.RoomService;
import com.karry.yl.service.elder.CheckInRecordsService;
import com.karry.yl.service.elder.ElderlyService;
import com.karry.yl.service.healthdata.HealthDataService;
import com.karry.yl.service.personnel.DepartmentService;
import com.karry.yl.service.services.MealService;
import com.karry.yl.service.services.RecordsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * 老人管理Controller
 */

@Controller
@RequestMapping("/gbElderly")
public class ElderlyGbController extends SuperController {

    private static final Logger LOG = LoggerFactory.getLogger(ElderlyGbController.class);
    @Autowired
    private BuildingService buildingService;
    @Autowired
    private RoomService roomService;
    @Autowired
    private BedService bedService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private MealService mealService;
    @Autowired
    private CheckInRecordsService checkInRecordsService;
    @Autowired
    private ElderlyService elderlyService;
    @Autowired
    private RecordsService recordsService;
    @Autowired
    private HealthDataService healthDataService;

    @RequestMapping("/elist")
    public String listUI(ModelMap map, HttpSession session) {
        session.removeAttribute("elderly-id");
        //查询所有楼宇 有楼宇才能查楼层
        List<Building> buildings = buildingService.selectList(new EntityWrapper<Building>().eq("orgId", currentUser.getOrgId()));
        if (buildings.size() > 0) {
            map.put("buildings", buildings);
            //查询第一个楼宇的所有楼层 有楼层一定有房间
            Room room = new Room();
            room.setOrgId(currentUser.getOrgId());
            room.setBuildingId(buildings.get(0).getId());
            List<Integer> floorList = roomService.selectRooms(room);
            Collections.sort(floorList);
            //查询第一个楼宇，对应第一个层的房间
            if (floorList.size() > 0) {
                map.put("floorList", floorList);
            } else {
                map.put("floorList", 0);
            }
            //查询第一个楼宇床位及入住情况
            Bed bed = new Bed();
            bed.setOrgId(currentUser.getOrgId());
            bed.setBuildingId(buildings.get(0).getId());
            List<Bed> bedsBuild = bedService.selectBedListByBuidFloor(bed);
            if (bedsBuild.size() > 0) {
                map.put("bedsBuild", bedsBuild);
            } else {
                map.put("bedsBuild", 0);
            }
            //查询第一个楼宇，第一个楼层床位及入住情况
            if (floorList.size() > 0) {
                bed.setFloor(floorList.get(0).toString());
                List<Bed> bedsFloor = bedService.selectBedListByBuidFloor(bed);
                if (bedsFloor.size() > 0) {
                    map.put("bedsFloor", bedsFloor);
                } else {
                    map.put("bedsFloor", 0);
                }
            } else {
                map.put("bedsFloor", 0);
            }
        } else {
            map.put("buildings", 0);
            map.put("floorList", 0);
            map.put("bedsBuild", 0);
            map.put("bedsFloor", 0);
        }
        return "elder/elderly/elist";
    }

    /*
     * 根据楼宇查询床位统计数据
     * **/
    @RequestMapping("/statisticsBuid")
    @ResponseBody
    public JsonResponse statisticsBuid(Bed bed) {
        bed.setOrgId(currentUser.getOrgId());
        bed.setFloor("");
        List<Bed> bedsBuild = bedService.selectBedListByBuidFloor(bed);
        Map map = new HashMap();
        map.put("bedsBuild", bedsBuild);
        return JsonResponse.success(map);
    }

    /*
     * 根据楼宇楼层查询床位统计数据
     * **/
    @RequestMapping("/statisticsFloor")
    @ResponseBody
    public JsonResponse statisticsFloor(Bed bed) {
        bed.setOrgId(currentUser.getOrgId());
        List<Bed> bedsFloor = bedService.selectBedListByBuidFloor(bed);
        Map map = new HashMap();
        map.put("bedsFloor", bedsFloor);
        return JsonResponse.success(map);
    }

    /*
     * 根据楼宇楼层查询房间
     * **/
    @RequestMapping("/selectRoomListByBuildFloor")
    @ResponseBody
    public JsonResponse selectRoomListByBuildFloor(Room room) {
        Map map = new HashMap();
        room.setOrgId(currentUser.getOrgId());
        List<Room> roomList = roomService.selectRoomListByBuildFloor(room);
        if (roomList.size() > 0) {
            map.put("roomList", roomList);
        } else {
            map.put("roomList", 0);
        }
        return JsonResponse.success(map);
    }

    /**
     * 根据楼宇楼层查询床位统计数据
     */
    @RequestMapping("/getFloorsByBid")
    @ResponseBody
    public JsonResponse getFloorsByBid(Room room) {
        Map map = new HashMap();
        room.setOrgId(currentUser.getOrgId());
        List<Integer> floorList = roomService.selectRooms(room);
        Collections.sort(floorList);
        if (floorList.size() > 0) {
            map.put("floorList", floorList);
        } else {
            map.put("floorList", 0);
        }
        return JsonResponse.success(map);
    }


    /**
     *根据房间id查询该房内床位信息
     * @param bed
     * @return
     */
    @RequestMapping("/getBedsByRid")
    @ResponseBody
    public JsonResponse getBedsByRid(Bed bed) {
        bed.setOrgId(currentUser.getOrgId());
        List<ElderlyBebs> bes = bedService.selectBedsByRid(bed);
            return JsonResponse.success(bes);
    }

    @RequestMapping("/ruzhu")
    public String addUI(Bed bed, ModelMap map) {
        bed.setOrgId(currentUser.getOrgId());
        Bed bedModeo = bedService.selectBedById(bed);
        List<Department> departments = departmentService.selectList(new EntityWrapper<Department>().eq("orgId", currentUser.getOrgId()).eq("isNursingDepartment", 1));
        List<Meal> meals = mealService.selectList(new EntityWrapper<Meal>().eq("orgId", currentUser.getOrgId()));
        map.put("bedModeo", bedModeo);
        map.put("departments", departments);
        map.put("meals", meals);
        return "elder/elderly/ruzhuadd";
    }

    /**
     * 根据老人信息查询入住信息
     * @param elderlyId
     * @param map
     * @return
     */
    @RequestMapping("/selectBedByElderId")
    @ResponseBody
    public JsonResponse selectBedByElderId(Long elderlyId, ModelMap map) {
        CheckInRecords checkIn = checkInRecordsService.selectOne(new EntityWrapper<CheckInRecords>().eq("orgId", currentUser.getOrgId()).eq("elderlyId", elderlyId));
        if (checkIn == null) {
            map.put("bedModeo", null);
        } else {
            Bed bed = new Bed();
            bed.setOrgId(currentUser.getOrgId());
            bed.setId(Long.parseLong(checkIn.getBedId()));
            Bed bedModeo = bedService.selectBedById(bed);
            map.put("bedModeo", bedModeo);
        }
        return JsonResponse.success(map);
    }


    /**
     * 查询老人的基本信息
     *
     * @param elderlyId
     * @param map
     * @return
     */
    @RequestMapping("/messageUI")
    public String messageUI(Long elderlyId, Integer type, ModelMap map, HttpSession session) {
        session.setAttribute("elderly-id", elderlyId);
        //根据老人id查询出老人信息
        Elderly elderly = elderlyService.selectById(elderlyId);
        map.put("elderly", elderly);
        //设置点击的类型，前端需要展示哪个
        map.put("type", type);
        //查询老人健康数据
        List<HealthData> healthDataList = healthDataService.selectByElderlyId(elderlyId);
        map.put("healthDataList", healthDataList);
        return "elder/elderly/message";
    }

    /**
     * 获取当前老人的服务记录
     *
     * @param page
     * @param limit
     * @param session
     * @return
     */
    @RequestMapping("/recordsList")
    @ResponseBody
    public LayTableResponse recordsList(int page, int limit, HttpSession session) {
        Long elderlyId = (Long) session.getAttribute("elderly-id");
        //查询服务记录
        Page<Records> recordsPage = recordsService.selectPage(new Page<>(page, limit), new EntityWrapper<Records>().eq("orgId", currentUser.getOrgId()).eq("elderlyId", elderlyId).orderBy("serviceDate", false));
        return new LayTableResponse(recordsPage.getRecords(), recordsPage.getTotal());
    }

    /**
     * 入住变更
     *
     * @param elderlyId
     * @param map
     * @return
     */
    @RequestMapping("/checkInUpdate")
    public String checkInUpdate(Long elderlyId, ModelMap map) {
        //根据老人id查询出老人信息
        Elderly elderly = elderlyService.selectById(elderlyId);
        map.put("elderly", elderly);
        List<Department> departments = departmentService.selectList(new EntityWrapper<Department>().eq("orgId", currentUser.getOrgId()).eq("isNursingDepartment", 1));
        map.put("departments", departments);
        List<Meal> meals = mealService.selectList(new EntityWrapper<Meal>().eq("orgId", currentUser.getOrgId()));
        map.put("meals", meals);
        List<Building> buildings = buildingService.selectList(new EntityWrapper<Building>().eq("orgId", currentUser.getOrgId()));
        map.put("buildings", buildings);
        //查询老人的入住记录
        CheckInRecords checkInRecords = checkInRecordsService.selectOne(new EntityWrapper<CheckInRecords>().eq("elderlyId", elderlyId));
        elderly.setBuildingNo(checkInRecords.getBuildingNo());
        elderly.setRoomNo(checkInRecords.getRoomNo());
        elderly.setBedNo(checkInRecords.getBedNo());
        return "elder/checkinrecords/checkInUpdate";
    }


    /**
     * 根据楼域id查询该楼宇有多少层
     *
     * @param buildingId
     * @return
     */
    @RequestMapping("/selectFloors")
    @ResponseBody
    public JsonResponse selectFloors(Long buildingId) {
        Building building = buildingService.selectById(buildingId);
        String floors = building.getFloors();
        return new JsonResponse(200, "楼层数", floors);
    }


    /**
     * 根据楼域id查询该楼宇有某层有多少个房间
     *
     * @param buildingId
     * @return
     */
    @RequestMapping("/selectRooms")
    @ResponseBody
    public JsonResponse selectRooms(Long buildingId, Integer floor) {
        Page<Room> roomPage = roomService.selectRoomPage(new Page<Room>(0, 10), currentUser.getOrgId(), buildingId, floor);
        return new JsonResponse(200, "房间", roomPage.getRecords());
    }

    /**
     * 根据楼域id查询该楼宇有某层有某个房间有多少床位
     *
     * @param buildingId
     * @param floor
     * @param roomId
     * @return
     */
    @RequestMapping("/selectBeds")
    @ResponseBody
    public JsonResponse selectBeds(Long buildingId, String floor, Long roomId) {
        List<Bed> beds = bedService.selectList(new EntityWrapper<Bed>().eq("orgId", currentUser.getOrgId()).eq("roomId", roomId).eq("buildingId", buildingId).eq("floor", floor).eq("status", 1));
        return new JsonResponse(200, "床位", beds);
    }



    @RequestMapping("/selectBedType")
    @ResponseBody
    public JsonResponse selectBedType(Long id) {
        Bed bed = bedService.selectById(id);
        return new JsonResponse(200, "床位", bed);
    }


}
